package com.xinghanlaser.applet.controller;

import com.xinghanlaser.applet.base.common.entity.ResponseEntity;
import com.xinghanlaser.applet.base.common.utils.RegexUtils;
import com.xinghanlaser.applet.service.IAdminService;
import com.xinghanlaser.applet.service.IPhoneCodeService;
import com.xinghanlaser.applet.vo.applet.DealerBindVO;
import com.xinghanlaser.applet.vo.applet.PasswordPutVO;
import com.xinghanlaser.applet.vo.applet.RegisterOrLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/7 14:06
 */
@RestController
@RequestMapping("/admin")
@Api(value = "登录管理", tags = "登录管理")
public class AdminController {

    @Resource
    private IAdminService service;

    @Resource
    private IPhoneCodeService phoneCodeService;

    @PostMapping("/phone-code")
    @ApiOperation("注册/登录普通用户")
    public ResponseEntity<String> registerOrLogin(@RequestBody @Valid RegisterOrLoginVO vo, HttpServletRequest request){
        // 校验验证码
        if (!phoneCodeService.validatedCode(vo.getPhone(), vo.getCode())) {
            return ResponseEntity.faultMsg("验证码不正确");
        }

        return service.registerOrLogin(vo, request);
    }

    @GetMapping("/phone-code/{phone}")
    @ApiOperation("发送验证码")
    public ResponseEntity<Void> sendCode(@PathVariable("phone") String phone){
        if (RegexUtils.isPhoneInvalid(phone)) {
            return ResponseEntity.faultMsg("手机号格式不正确");
        }

        phoneCodeService.generateAndSendCode(phone);

        return ResponseEntity.okMsg("发送成功");
    }

    @PostMapping("/dealer/bind")
    @ApiOperation("用户绑定经销商")
    public ResponseEntity<Void> dealerBind(@RequestBody @Valid DealerBindVO vo){
        return service.dealerBind(vo);
    }

    @PutMapping("/password")
    @ApiOperation("修改用户密码")
    public ResponseEntity<Void> updatePassword(@RequestBody @Valid PasswordPutVO vo){
        // 校验验证码
        if (!phoneCodeService.validatedCode(vo.getPhone(), vo.getCode())) {
            return ResponseEntity.faultMsg("验证码不正确");
        }

        return service.updatePassword(vo);
    }
}
